﻿using System;
using System.Security.Cryptography;

namespace MT.Common.Helper
{
    public  class RandomHelper
    {
        public static string CreateToken(int length)
        {
            byte[] data = new byte[length * 2];
            RNGCryptoServiceProvider rng = new RNGCryptoServiceProvider();
            rng.GetNonZeroBytes(data);
            string sessionKey = System.Convert.ToBase64String(data);

            if (sessionKey.Length > length)
                sessionKey = sessionKey.Substring(0, length);

            return sessionKey.Replace("+", "q").Replace('/', 'd');
        }

        public static string CreateToken(int length, string key)
        {
            var token = CreateToken(length) + key;
            MD5CryptoServiceProvider md5Hasher = new MD5CryptoServiceProvider();
            byte[] data = md5Hasher.ComputeHash(System.Text.Encoding.UTF8.GetBytes(token));
            System.Text.StringBuilder sBuilder = new System.Text.StringBuilder();
            for (int i = 0; i < data.Length; i++)
            {
                sBuilder.Append(data[i].ToString("x2"));
            }
            return sBuilder.ToString().ToLower().Substring(8, 16);
        }


        public static string BuildGeneratedCode(string prefix, int length = 16)
        {
            string code = prefix + DateTime.Now.ToString("yyMMddHH") + Math.Abs(Guid.NewGuid().GetHashCode()).ToString();
            if (code.Length < length)
            {
                int len = length - code.Length;
                for (int i = 0; i < len; i++)
                {
                    code += new Random(Guid.NewGuid().GetHashCode()).Next(0, 10).ToString();
                }
            }
            else
            {
                code = code.Substring(0, length);
            }
            return code;
        }

        public static string CreatePhoneVerificationToken()
        {
            Random rnd = new Random(Guid.NewGuid().GetHashCode());
            int token = rnd.Next(100000, 999999);

            return token.ToString();
        }

        /// <summary>
        /// 随机种子值
        /// </summary>
        /// <returns></returns>
        public static int GetRandomSeed()
        {
            byte[] bytes = new byte[4];
            RNGCryptoServiceProvider rng = new RNGCryptoServiceProvider();
            rng.GetBytes(bytes);
            return BitConverter.ToInt32(bytes, 0);
        }
    }
}
